package com.waitingresult.common.base.handler;

import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowException;
import com.alibaba.csp.sentinel.slots.system.SystemBlockException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.waitingresult.common.base.model.Result;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * All right reserved,Designed By WangShuai
 * <p>
 * 自定义BlockException的返回值
 *
 * @author : WangShuai
 * @version : V1.0
 * @ClassName : SentinelBlockHandler
 * @Description :
 * @date : 2021/9/26 16:18
 */
@Component
public class SentinelBlockHandler implements BlockExceptionHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, BlockException e) throws Exception {
        Result<Object> result = new Result<>();
        if (e instanceof FlowException) {
            result = Result.error("服务限流", e.getMessage());
        } else if (e instanceof DegradeException) {
            result = Result.error("服务降级", e.getMessage());
        } else if (e instanceof ParamFlowException) {
            result = Result.error("热点限流", e.getMessage());
        } else if (e instanceof SystemBlockException) {
            result = Result.error("系统规则限制", e.getMessage());
        } else if (e instanceof AuthorityException) {
            result = Result.error("授权不通过", e.getMessage());
        }
        response.setStatus(500);
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-Type", "application/json;charset=utf-8");
        response.setContentType("application/json;charset=utf-8");

        new ObjectMapper()
                .writeValue(response.getWriter(), result);
    }

    @PostConstruct
    public void init() {
        new SentinelBlockHandler();
    }
}
